# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import AccessError, UserError, ValidationError
import odoo.addons.decimal_precision as dp

class PriceListSaleOrder(models.Model):
    _inherit = 'sale.order'

    # 搜尋銷售明細的備註，待整合
    search_remarks = fields.Char(related='order_line.remarks')
    search_partner_mobile = fields.Char(related='partner_id.mobile')
    search_partner_phone = fields.Char(related='partner_id.phone')
    key_in_user = fields.Many2one(comodel_name='res.users', string='製單人員', default=lambda self: self.env.uid, readonly=True)
    remarks = fields.Text(string='收貨備註')
    show_product_image = fields.Boolean(string='列印產品圖片')

    @api.multi
    def action_confirm(self):
        res = super(PriceListSaleOrder, self).action_confirm()
        purchase_order_id = self.env['purchase.order'].search([('origin','=',self.name),('state','=','draft')],limit=1)
        if purchase_order_id:
            for line in purchase_order_id:
                line.remarks = self.remarks
                line.client_order_ref = self.client_order_ref
        elif not purchase_order_id:
            raise ValidationError(u'錯誤，採購詢價單未建立')
        return res

    def action_unlock(self):
        self.state = 'sale'

    # 取消銷售訂單時刪除課程清單
    @api.multi
    def action_cancel(self):
        res = super(PriceListSaleOrder, self).action_cancel()
        if len(self.invoice_ids) > 0:
            for line in self.invoice_ids:
                if line.state not in ('cancel'):
                    raise ValidationError(u'錯誤，此銷售單還有發票未手動取消')

        if len(self.picking_ids) > 0:
            for line in self.picking_ids:
                if line.state in 'done':
                    raise ValidationError(u'錯誤!，此銷售單已經出貨，不能夠取消銷售訂單')
        return res

class PriceListSaleOrderLine(models.Model):
    _inherit = 'sale.order.line'

    price_list = fields.Text(string='價格表')
    group_lock = fields.Boolean(string='業務邏輯用變數')
    yifeng_price_unit = fields.Float(string='單價', related='price_unit', readonly=True)
    remarks = fields.Char(string='備註')

    @api.multi
    @api.onchange('product_id')
    def product_id_change(self):
        res = super(PriceListSaleOrderLine, self).product_id_change()

        if self.product_id is False:
            return res
        else:

            price_list = self.env['product.pricelist.item'].search(
                [('product_tmpl_id', '=', self.product_id.product_tmpl_id.id),('pricelist_id', '=', self.order_id.pricelist_id.id)])
            total_text = ""
            for line in price_list:
                text_show = " %i 個：每一個 %i 元 \n" % (line.min_quantity, line.fixed_price)
                total_text += text_show

            self.price_list = total_text

            if self.env.user.has_group('sales_team.group_sale_manager'):
                self.group_lock = False
            else:
                self.group_lock = True
            del_type = self.env.ref('stock_dropshipping.route_drop_shipping')
            self.route_id = del_type.id
            return res

    @api.multi
    def _prepare_order_line_procurement(self, group_id=False):
        res = super(PriceListSaleOrderLine, self)._prepare_order_line_procurement(group_id=False)
        res.update({'price_unit': self.yifeng_price_unit * self.discount})
        return res